package hl.demosample.app.weight.downloadpicture;

import android.content.Context;
import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.view.WindowManager;

public class DensityUtil {

    public static float scale = 0.0f;
    // 屏幕宽度（像素）
    public static int screenWidth;
    // 屏幕高度（像素）
    public static int screenHeight;

    public static float getScale() {
        //等于 scale=dm.density;
        scale =  Resources.getSystem().getDisplayMetrics().density / 160;
        return scale;
    }

    /**
     * 将px转换为dp值
     */
    public static int px2dp(float pxValue) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将dp转换为px
     */
    public static int dp2px(float dipValue) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 将px转换为sp
     */
    public static int px2sp(float pxValue) {
        final float fontScale = Resources.getSystem().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp转换为px
     */
    public static int sp2px(float spValue) {
        final float fontScale = Resources.getSystem().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public static int getScreenWidth(Context context) {
        if(screenWidth>0){
            return screenWidth;
        }else{
            WindowManager windowManager = (WindowManager) context.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics metric = new DisplayMetrics();
            windowManager.getDefaultDisplay().getMetrics(metric);
            screenWidth = metric.widthPixels;
            return metric.widthPixels;
        }
    }

    public static int getScreenHeight(Context context) {
        if(screenHeight>0){
            return screenHeight;
        }else{
            WindowManager windowManager = (WindowManager) context.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics metric = new DisplayMetrics();
            windowManager.getDefaultDisplay().getMetrics(metric);
            screenHeight = metric.heightPixels;
            return metric.heightPixels;
        }
    }

    public static float getScreenRatio(Context context) {
        return ((float) getScreenHeight(context)) / ((float) getScreenWidth(context));
    }
}